<?php
namespace Ayhome\Suite;

use think\Db;
use think\facade\Config;
use think\facade\Env;

use think\swoole\template\Timer;
use XCron\CronExpression;
class Crontab  extends Timer
{
  public $config;
  public function initialize($args)
  {
    $cfg = Config::pull('suite');

    $this->config = $cfg['crontab'];
    $this->createTask();

  }

  public function run()
  {
    $tasks = $this->config['tasks'];
    foreach ($tasks as $k) {
      $cron = CronExpression::factory($k['cron']);
      $crontime = $cron->getNextRunDate('now',-1,true)->getTimestamp();
      if ($crontime == time()) {
        $this->runTask($k);
      }
    }
  }

  public function runTask($cron = '')
  {
    if ($cron['type'] == 'remote' && $cron['url']) {
      $uri  = parse_url($cron['url']);
      $host = $uri['host'];
      $path = $uri['path'];
      
      $client = new \GuzzleHttp\Client();
      $res    = $client->request('GET', $cron['url']);
    } elseif ($cron['type'] == 'class' || $cron['type'] == 'local') {
      $cls_arr = explode("\\", $cron['url']);
      $cls_len = count($cls_arr);
      $method = $cls_arr[$cls_len-1];

      $namespace = '';
      for ($i=0; $i < $cls_len-1; $i++) { 
        $namespace .= "\\".$cls_arr[$i];
      }
      $ap = new $namespace();
      $ap->$method();

      if ($this->config['database']) {
        $u = array();
        $u['utime'] = time();
        Db::name($this->config['database'])
          ->where('id', $cron['id'])
          ->update($u);
      }

    }
  }

  function createTask(){
    if ($this->config['database']) {
      $tasks                 = Db::name($this->config['database'])->select();
      $this->config['tasks'] = $tasks;
    }
  }
}